import React, { useState, useEffect, useRef } from 'react'
import { Button, Form, Input, Space, Steps, Modal, message } from 'antd'
import _, { functions } from 'lodash'
import CountTimeDown from './CountTimeDown'
import Negotiate from './negotiate'
import { CloseCircleFilled } from '@ant-design/icons'
import '../style/style.less'
import moment from 'moment';
import { getDateTime2 } from '@/utils/getTimes'

const { Step } = Steps

const ChargebackSteps = (props) => {
  const negotiateRef = useRef()
  const [stepData, setStepData] = useState([])
  const [current, setCurrent] = useState(0)
  const [moneyStatus, setMoneyStatus] = useState("N")
  const [salesStatus, setSalesStatus] = useState(1)
  const [date, setDate] = useState(null)
  const [visible, setVisible] = useState(false)
  const [goodVisible, setGoodVisible] = useState(false)
  const [logVisible, setLogVisible] = useState(false)
  const [logisticsInformation, setLogisticsInformation] = useState([])
  const [loading, setLoading] = useState([])
  let shopOrderDetailId = props.dataSource.orderDetailVo.shopOrderDetailId

  useEffect(() => {
    Minutes()
    getStepData()
  }, [loading])

  /**
   * 倒计时实现
   * @constructor
   */
  let Minutes = () => {
    let date = new Date(props.countdown)
    let min = date.getMinutes()
    date.setMinutes(min)
    let newdate = date.toLocaleString('chinese', { hour12: false })
    setDate(newdate)
  }
  let getStepData = () => {
    const { moneyStatus, salesStatus, autoAgreeRefund, dataSource, countdown } = props
    let stepData = []
    let current = 0
    switch (parseInt(salesStatus)) {
      case 1:
        switch (moneyStatus) {
          case 'Y':
            stepData = [
              {
                title: '买家发起退款申请',
                description: dataSource.createTime,
              },
              {
                title: (
                    <div className="steps-timer">
                      <span>商家处理</span>
                      {
                        autoAgreeRefund === 0 ? (<span>剩余
                        < CountTimeDown endTime={countdown} /></span>) : null
                      }
                    </div>
                ),
                description: (
                    <Space>
                      <Button type='primary' size="middle" loading={loading[0]} onClick={() => refundConfirmGood(0)}>
                        同意
                      </Button>
                      <Button type='default' size="middle" loading={loading[1]} onClick={() => refundRefuse(1)}>
                        拒绝
                      </Button>
                      <Button type='default' size="middle" loading={loading[2]} onClick={() => negoHistory(2)}>
                        协商历史
                      </Button>
                      {
                        autoAgreeRefund === 0 ? <Button style={{ zIndex: 2 }} type='primary' danger size="middle" loading={loading[3]} onClick={() => refundHangUp(3)}>
                          纠纷处理开启
                        </Button> : <Button type='primary' danger size="middle" >
                          纠纷处理中...
                        </Button>
                      }
                    </Space>
                ),
              },
              {
                title: '买家寄回商品',
                description: dataSource.sendGoodsTime,
              },
              {
                title: '商家确认收货',
                description: dataSource.refundTime,
              },
              {
                title: '完成',
                description: dataSource.refundTime,
              },
            ]
            current = 1
            break
          case 'N':
            stepData = [
              {
                title: '买家发起退款申请',
                description: dataSource.createTime,
              },
              {
                title: (
                    <div className="steps-timer">
                      <span>商家处理</span>
                      {
                        autoAgreeRefund === 0 ? (<span>剩余
                        <CountTimeDown endTime={countdown} /></span>) : null
                      }
                    </div>
                ),
                description: (
                    <Space>
                      <Button type='primary' size="middle" loading={loading[0]} onClick={() => refundConfirm(0)}>
                        同意
                      </Button>
                      <Button type='default' size="middle" loading={loading[1]} onClick={() => refundRefuse(1)}>
                        拒绝
                      </Button>
                      <Button type='default' size="middle" loading={loading[2]} onClick={() => negoHistory(2)}>
                        协商历史
                      </Button>
                      {autoAgreeRefund === 0 ? <Button type='primary' danger size="middle" loading={loading[3]} onClick={() => refundHangUp(3)}>
                        纠纷处理开启
                      </Button> : <Button type='primary' danger size="middle"  >
                        纠纷处理中...
                      </Button>}
                    </Space>
                ),
              },
              {
                title: '完成',
                description: dataSource.refundTime,
              },
            ]
            current = 1
            break
        }
        break
      case 2:
        switch (moneyStatus) {
          case 'Y':
            stepData = [
              {
                title: '买家发起退款申请',
                description: dataSource.createTime,
              },
              {
                title: `商家同意退款`,
                description: dataSource.returnGoodsTime,
              },
              {
                title: '买家寄回商品',
                description: dataSource.sendGoodsTime,
              },
              {
                title: '商家确认收货',
                description: dataSource.refundTime,
              },
              {
                title: '完成',
                description: dataSource.refundTime,
              },
            ]
            current = 1
            break
        }
        break
      case 3:
        stepData = [
          {
            title: '买家发起退款申请',
            description: dataSource.createTime,
          },
          {
            title: `商家同意退款`,
            description: dataSource.returnGoodsTime,
          },
          {
            title: '买家寄回商品',
            description: dataSource.sendGoodsTime,
          },
          {
            title: '商家确认收货',
            subTitle: dataSource.refundTime,
            description: (
                <Space>
                  <Button type='primary' size="middle" onClick={onLogistics}>
                    查看物流
                  </Button>

                  <Button type='primary' size="middle" onClick={confirmGood}>
                    收货
                  </Button>
                  <Button type='default' size="middle" onClick={openGoodDialog}>
                    拒绝
                  </Button>
                </Space>
            ),
          },
          {
            title: '完成',
            description: dataSource.refundTime,
          },
        ]
        current = 3
        break
      case 9:
        switch (moneyStatus) {
          case 'N':
            stepData = [
              {
                title: '买家发起退款申请',
                description: dataSource.createTime,
              },
              {
                title: `商家同意退款`,
                description: dataSource.returnGoodsTime,
              },
              {
                title: '退款成功',
                description: dataSource.refundTime,
              },
            ]
            current = 2
            break
          case 'Y':
            stepData = [
              {
                title: '买家发起退款申请',
                description: dataSource.createTime,
              },
              {
                title: `商家同意退款`,
                description: dataSource.returnGoodsTime,
              },
              {
                title: '买家寄回商品',
                description: dataSource.sendGoodsTime,
              },
              {
                title: '商家确认收货',
                description: dataSource.refundTime,
              },
              {
                title: '退款成功',
                description: dataSource.refundTime,
              },
            ]
            current = 4
            break
        }
        break
      case 4:
        stepData = [
          {
            title: '买家发起退款申请',
            description: dataSource.createTime,
          },
          {
            title: `商家拒绝退款`,
            description: dataSource.returnGoodsTime,
          },
          {
            title: '退款失败',
            description: dataSource.refundTime,
          },
        ]
        current = 2
        break
      case 5:
        stepData = [
          {
            title: '买家发起退款申请',
            description: dataSource.createTime,
          },
          {
            title: `商家同意退款`,
            description: dataSource.returnGoodsTime,
          },
          {
            title: '买家超时未寄回商品',
            description: dataSource.sendGoodsTime,
          },
          {
            title: '退款失败',
            description: dataSource.refundTime,
          },
        ]
        current = 3
        break
      case 6:
        stepData = [
          {
            title: '买家发起退款申请',
            description: dataSource.createTime,
          },
          {
            title: `商家同意退款`,
            description: dataSource.returnGoodsTime,
          },
          {
            title: '买家已寄回商品',
            description: dataSource.sendGoodsTime,
          },
          {
            title: '商家拒绝收货',
            description: dataSource.refundTime,
          },
          {
            title: '退款失败',
            description: dataSource.refundTime,
          },
        ]
        current = 4
        break
      case 7:
        stepData = [
          {
            title: '买家发起退款申请',
            description: dataSource.createTime,
          },
          {
            title: `用户取消退款`,
            description: dataSource.refundTime,
          },
        ]
        current = 1
        break
      case 0:
        stepData = [
          {
            title: '买家发起退款申请',
            description: dataSource.createTime,
          },
          {
            title: `退款关闭`,
            description: dataSource.refundTime,
          },
        ]
        current = 1
        break
    }
    setStepData(stepData)
    setCurrent(current)
  }
  let refundHangIng = () => {
    // React.$confirm({
    //   title: '纠纷处理开启后将暂停超时退款，纠纷处理完成后需手动处理订单',
    //   onOk: () => {

    //   },
    // })
  }
  let refundHangUp = (index) => {
    const { salesId } = props
    setLoading((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[index] = true;
      return newLoadings;
    })
    Modal.confirm({
      title: '纠纷处理开启后将暂停超时退款，纠纷处理完成后需手动处理订单，您确认开启吗？',
      onOk: () => {
        React.$postJson('management/shopSalesReturn/updateAutoAgreeRefundState/Json', {
          autoAgreeRefund: 1,//0-开启, 1-挂起
          shopSalesReturnId: salesId//退款订单id
        }).then(
            (res) => {
              if (res.code === 0) {
                message.info("操作成功")
                window.location.reload()
              }
            }
        )
      },
      onCancel: () => {
        setLoading((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[index] = false;
          return newLoadings;
        })
      }
    })
  }

  let negoHistory = (index) => {
    setLoading((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[index] = true;
      return newLoadings;
    })
    negotiateRef.current.open()
  }
  let onLoading = (index) => {
    setLoading((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[index] = false;
      return newLoadings;
    })
  }
  let refundConfirmGood = (index) => {
    setLoading((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[index] = true;
      return newLoadings;
    })
    Modal.confirm({
      title: '您确认同意退款退货吗？',
      onOk: () => {
        const { salesId } = props
        React.$post('management/shopSalesReturn/refundConfirmGood', { salesId }).then(
            (res) => {
              if (res.code === 0) {
                message.info("退款退货成功")
                window.location.reload()
              }
            }
        )
      },
      onCancel: () => {
        setLoading((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[index] = false;
          return newLoadings;
        })
      }
    })
  }
  let refundConfirm = (index) => {
    const { salesId } = props
    setLoading((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[index] = true;
      return newLoadings;
    })
    Modal.confirm({
      title: '您确认退款吗？',
      onOk: () => {
        React.$post('management/shopSalesReturn/refundConfirm', { salesId }).then(
            (res) => {
              if (res.code === 0) {
                message.info("退款成功")
                window.location.reload()
              }
            }
        )
      },
      onCancel: () => {
        setLoading((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[index] = false;
          return newLoadings;
        })
      }
    })
  }
  let refundRefuse = (index) => {
    setLoading((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[index] = true;
      return newLoadings;
    })
    Modal.confirm({
      title: '您确认拒绝退款吗？',
      onOk: () => {
        setVisible(true)
        setLoading((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[index] = false;
          return newLoadings;
        })
      },
      onCancel: () => {
        setLoading((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[index] = false;
          return newLoadings;
        })
      }
    })
  }
  let handleCancel = () => {
    setVisible(false)
  }
  let saveRefundRefuse = (value) => {
    const { salesId } = props
    React.$post('management/shopSalesReturn/refundRefuse', {
      salesId,
      ...value,
    }).then((res) => {
      if (res.code === 0) {
        message.info("拒绝退款成功")
        window.history.back()
      }
    })
  }
  let confirmGood = () => {
    Modal.confirm({
      title: '您确认收货吗？',
      onOk: () => {
        const { salesId } = props
        React.$post('management/shopSalesReturn/storeConfirmGood', { salesId }).then(
            (res) => {
              if (res.code === 0) {
                message.info("确认收货成功")
                window.location.reload()
              }
            }
        )
      },
    })
  }
  let openGoodDialog = () => {
    setGoodVisible(true)
  }
  let saveRefuseGood = (value) => {
    const { salesId } = props
    React.$post('management/shopSalesReturn/storeRefuseGood', { salesId, ...value }).then(
        (res) => {
          if (res.code === 0) {
            message.info("拒绝收货成功")
            setGoodVisible(false)
            window.history.back()
          }
        }
    )
  }
  let logDialogCancel = () => {
    setLogisticsInformation(null)
    setLogVisible(false)
  }
  let onLogistics = async () => {
    const {
      dataSource: { shopSalesReturnId },
    } = props
    React.$post(`management/shopOrderInfo/checkLogisticsRefund/${shopSalesReturnId}`).then((response) => {
      if (response.code === 0 && response.data) {
        let {
          msg: { context },
        } = response.data
        context = context
            ? context.map((v) => {
              let time = v.time * 1000
              time = new Date(parseInt(time))
              time = getDateTime2(time)
              return {
                ...v,
                time,
              }
            })
            : null
        setLogisticsInformation(context)
        setLogVisible(true)
      } else {
        message.info("暂无物流信息")
      }
    })
  }

  return (
      <div>
        {parseInt(salesStatus) !== 0 && (
            <Steps progressDot current={current}>
              {_.map(stepData, (v, i) => {
                return (
                    <Step
                        key={i}
                        title={v.title}
                        description={
                          <div className={'order-details-time'}>{v.description}</div>
                        }
                    />
                )
              })}
            </Steps>
        )}
        {parseInt(salesStatus) === 7 && (
            <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
              <CloseCircleFilled
                  style={{ color: '#2b6dea', fontSize: 50, marginRight: 20 }}
              />
              <div>
                <div style={{ fontSize: 14, color: '#2b6dea' }}>退款取消</div>
              </div>
            </div>
        )}
        {parseInt(salesStatus) === 0 && (
            <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
              <CloseCircleFilled
                  style={{ color: '#2b6dea', fontSize: 50, marginRight: 20 }}
              />
              <div>
                <div style={{ fontSize: 14, color: '#2b6dea' }}>退款关闭</div>
                <div style={{ fontSize: 14, color: '#2b6dea', marginTop: 5 }}>
                  <span style={{ marginRight: 10 }}>原因:</span>
                  <span>{refuseComment}</span>
                </div>
              </div>
            </div>
        )}
        <Modal
            open={visible}
            title={'拒绝退款'}
            handleCancel={handleCancel}
            footer={null}
            width={400}>
          <Form onFinish={saveRefundRefuse}>
            <Form.Item
                name="refuseReason"
                label="备注"
                rules={[{ required: true }]}>
              <Input.TextArea maxLength={20} showCount allowClear />
            </Form.Item>
            <Form.Item>
              <div
                  style={{
                    display: 'flex',
                    justifyContent: 'flex-end',
                    marginBottom: -30,
                  }}>
                <Space>
                  <Button onClick={handleCancel}>取消</Button>
                  <Button type="primary" htmlType="submit">
                    确认
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
            open={goodVisible}
            title={'拒绝收货'}
            handleCancel={() => setGoodVisible(false)}
            footer={null}
            width={400}>
          <Form onFinish={saveRefuseGood}>
            <Form.Item
                name="refuseReason"
                label="备注"
                rules={[{ required: true }]}>
              <Input.TextArea maxLength={20} allowClear showCount />
            </Form.Item>
            <Form.Item>
              <div
                  style={{
                    display: 'flex',
                    justifyContent: 'flex-end',
                    marginBottom: -30,
                  }}>
                <Space>
                  <Button onClick={() => setGoodVisible(false)}>
                    取消
                  </Button>
                  <Button type="primary" htmlType="submit">
                    确认
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
            open={logVisible}
            onCancel={logDialogCancel}
            footer={null}
            title={'跟踪物流'}>
          <div style={{ height: 500, overflowY: 'auto' }}>
            {logisticsInformation && (
                <Steps
                    progressDot
                    current={logisticsInformation.length - 1}
                    direction="vertical">
                  {logisticsInformation.map((v,i) => {
                    return <Step key={i} title={v.time} description={v.desc} />
                  })}
                </Steps>
            )}
            {!logisticsInformation && <span>暂无物流信息</span>}
          </div>
          <Space
              style={{
                display: 'flex',
                justifyContent: 'center',
                marginTop: 20,
              }}>
            <Button type={'primary'} onClick={logDialogCancel}>
              确定
            </Button>
          </Space>
        </Modal>
        <Negotiate ref={negotiateRef} shopOrderDetailId={shopOrderDetailId} onLoading={() => onLoading(2)}></Negotiate>
      </div>
  )
}

export default ChargebackSteps;
